class User < ActiveRecord::Base
  has_one:account
  has_many:account_records
  has_many:post_info
  has_many:order
  has_many:shop
  has_many:productcomment
  
  validates_presence_of :nick_name,:email
  validates_uniqueness_of:nick_name,:email
  
  def validate
    errors.add_ro_base("Missing password" ) if hashed_password.blank?
  end
  
  def self.authenticate(email,password)
    user=self.find_by_email(email)
    if user
      expected_password=encrypted_password(password,user.salt)
      if user.hashed_password!=expected_password
        user=nil
      end
    end
    return user
  end
  
  def self.authenticate_by_id(id,password)
    user=self.find(id)
    if user
      expected_password=encrypted_password(password,user.salt)
      if user.hashed_password!=expected_password
        user=nil
      end
    end
    return user
  end
  
  def password
    @password
  end
  
  def password=(pwd)
    @password=pwd
    return if pwd.blank?
    create_new_salt
    self.hashed_password=User.encrypted_password(self.password,self.salt)
  end
  
  private
  
  def self.encrypted_password(password,salt)
    string_to_hash=password+"wibble"+salt
    Digest::SHA1.hexdigest(string_to_hash)
  end
  
  def create_new_salt
    self.salt=self.object_id.to_s+rand.to_s
  end
end
